#include <mips/regdef.h>

#define 	fp 	$fp

.globl readEncode
.align 2
.ent readEncode



    .data
read:
    .space 4
    .align 2
    .text

    .data
aux:
    .space 1
    .align 2
    .text


readEncode:
	.frame fp,32,ra
	subu sp, sp, 32 # creo stack
	sw fp, 28(sp)
	sw gp, 24(sp)
	sw ra, 20(sp)
	.set reorder
	.cprestore 24
	move fp, sp
	
	li t1,4 # Maximo Size posible
	li t4,0 # Contador de lectura
	li t5,0 # size counter
	sw t2, 32(sp) # fd

	b readByte

iterar:
	sw t6, aux($0)
	beq t6,zero,exit_eof # !eof

	add t5,t5,1 # Contador de size

	lw t0, 36(fp) # cargo la direccion de la base del puntero
	sll t4, t4, 2 # multiplico por 4 para obtener el nuevo offset

	move sp, t0
	add sp, sp, t4
	sb t6, 0(sp) # avanzo al nuevo offset libre y guardo el char

	blt t1,t5,iterar # while size < 3
	
	b exit_success

exit_eof:
	li v0, -1
	b exit

exit_success:
	move v0, t5
	b exit

exit:
	move sp, fp
	lw ra,20(sp)
	lw fp, 20(sp) # destruyo stack
	addu sp, sp, 32
	jr ra

readByte:
    li   v0, 14  # system call for reading from file
    move t2, a0  # file descriptor
    la   a1, aux  # address of buffer from which to read
    li   a2, 1   # hardcoded buffer length
    syscall       # read from file
   	b iterar


.end readEncode
